<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body class="body" style="width: 100vw; height: 100vh; background: darkgray; margin: 0px; overflow: hidden;">
    <div class="box" style="height: 100px; width: 100px; background: skyblue; margin: 8px;"></div>
    <script>
        const box = document.querySelector('.box')
        const body = document.querySelector('.body')
        let mouseX = 0
        let mouseY = 0
        let boxOffsetLeft = 0
        let boxOffsetTop = 0
        let isDrag = false
        box.addEventListener('mousedown', function (e) {
            mouseX = e.clientX
            mouseY = e.clientY

            boxOffsetLeft = e.target.offsetLeft
            boxOffsetTop = e.target.offsetTop
            box.style.position = 'absolute'
            box.style.cursor = 'move'
            isDrag = true

            body.addEventListener('mousemove', function (e) {
                if (!isDrag) return
                const left = boxOffsetLeft + (e.clientX - mouseX)
                const top = boxOffsetTop + (e.clientY - mouseY)

                const bodyOffsetWidth = body.offsetWidth
                const bodyOffsetHeight = body.offsetHeight

                console.log(left, body.clientWidth, box.offsetWidth)
                box.style.left = (left < 0 ? 0 :  left > (bodyOffsetWidth - box.offsetWidth) ?  (bodyOffsetWidth - box.offsetWidth - 16) : left) + 'px'
                box.style.top = (top < 0 ? 0 : top > (bodyOffsetHeight - box.offsetHeight) ? (bodyOffsetHeight - box.offsetHeight -16) : top ) + 'px'

            })
        })

        window.addEventListener('mouseup', function(e) {
            isDrag = false
            box.style.cursor = 'default'
        })

    </script>
</body>

</html>